package com.epro.dx.activity.order.fragment;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.epro.dx.R;
import com.epro.dx.activity.CancelOrderActivity;
import com.epro.dx.activity.CheckoutActivity;
import com.epro.dx.activity.creditcard.AddCreditCardActivity;
import com.epro.dx.activity.creditcard.CreditCardListActivity;
import com.epro.dx.activity.order.MyOrdersActivity;
import com.epro.dx.activity.order.OrderDetailActivity;
import com.epro.dx.activity.order.OrderPlaceActivity;
import com.epro.dx.activity.order.ShippingTrackingActivity;
import com.epro.dx.adapter.MyOrderListAdapter;
import com.epro.dx.adapter.MyOrderListAdapter.OrderOperatListenner;
import com.epro.dx.fragment.BaseFragment;
import com.epro.dx.fragment.BaseLoadAndEmptyDataFragment;
import com.epro.dx.listenner.GetCreditCardInfoListenner;
import com.epro.dx.listenner.OrderOperateCompleteListenner;
import com.epro.dx.listenner.PaymentMethodDialogOnClickListenner;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshBase.Mode;
import com.epro.dx.pullview.PullToRefreshBase.OnRefreshListener2;
import com.epro.dx.pullview.PullToRefreshListView;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.GetCreditCardInfoAsyncTask;
import com.epro.dx.util.PaymentMethodDialogUtils;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.HitBuilders.EventBuilder;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.internal.or;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.OrderServiceProvider;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.CreditCardInfo;
import com.weipu.common.facade.model.Operator;
import com.weipu.common.facade.model.OrderItemModel;
import com.weipu.common.facade.model.Package;
import com.weipu.common.facade.model.SimpleCreditCard;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.GlobalConfig;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

public class MyOrderFragment extends BaseLoadAndEmptyDataFragment implements
        OrderOperatListenner {
    private static final String TAG = "TAG";
    private PullToRefreshListView orderListView;
    private int pageSize = 10;
    private View rootView;
    // 订单数据存储集合
    private ArrayList<OrderItemModel> allPageOrdersList = new ArrayList<OrderItemModel>();
    private ArrayList<OrderItemModel> morePageOrdersList = new ArrayList<OrderItemModel>();

    private String orderStatus = "All";

    private OrderServiceProvider orderServiceProvider = ProviderFactory
            .createOrderServiceProvider();

    private int pageIndex = 1;

    private MyOrderListAdapter adapter;

    private Activity mContext;

    private OrderOperateCompleteListenner orderComListenner;

    private int clickItemIndex = -1;
    private Tracker tracker;
    private EventBuilder eventBuilder;

    @SuppressLint("ValidFragment")
    public MyOrderFragment(Activity context, String status) {
        this.mContext = context;
        this.orderStatus = status;
    }

    public MyOrderFragment() {

    }

    @Override
    public void onAttach(Activity activity) {
        this.mContext = activity;
        super.onAttach(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Logger.i(TAG, "rootView: " + rootView);
        tracker = DXApplication.getContext().getTracker(TrackerName.APP_TRACKER);
        eventBuilder = new HitBuilders.EventBuilder().setCategory("Click Button");
        if (rootView == null) {
//			rootView = View.inflate(getActivity(),
//					R.layout.myorder_fragment_base, null);
            rootView = inflate(R.layout.myorder_fragment_base);
            intView(rootView);
            initData();
            initEvent();
            AsyncTaskUtil.executeTask(new OrdersListAsyncTask(pageIndex, false,
                    false));
        }
        if (savedInstanceState != null) {
            orderStatus = savedInstanceState.getString("type");
        }
        if (null == mContext) {
            mContext = getActivity();
        }
        Logger.i(TAG, "status: " + orderStatus);
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    public void setView() {
        this.rootView = null;
    }

    public void setOrderOperateCompleteListenner(
            OrderOperateCompleteListenner orderComListenner) {
        this.orderComListenner = orderComListenner;
    }

    private void intView(View rootView) {
        orderListView = (PullToRefreshListView) rootView
                .findViewById(R.id.lv_myorder_basefragment_orderlist);
        if (null != errorLayout) {
            errorLayout.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    hideAllLayout();
                    AsyncTaskUtil.executeTask(new OrdersListAsyncTask(1, false,
                            true));

                }
            });
        }
//		loadingLayout = (LinearLayout) rootView
//				.findViewById(R.id.loading_layout);
//		noDataSuggest = (TextView) rootView.findViewById(R.id.tv_empty);
//		noDataIcon = (ImageView) rootView.findViewById(R.id.pic_empty);
    }

    /**
     * 加载数据
     */
    public void initData() {
        // 给listView添加适配器
        allPageOrdersList = new ArrayList<OrderItemModel>();
        adapter = new MyOrderListAdapter(getActivity(), allPageOrdersList,
                orderListView, orderStatus);
        adapter.setOperatListenner(this);
        orderListView.setAdapter(adapter);
    }

    /**
     * 取消 支付 确认收获动作后刷新Order
     */
    public void refreshOrderStatus(boolean isCurrentFragment, int oprationType) {
        if (isCurrentFragment) {
            if (-1 != clickItemIndex && null != allPageOrdersList
                    && allPageOrdersList.size() > clickItemIndex) {
                OrderItemModel orderItemModel = allPageOrdersList
                        .get(clickItemIndex);
                Logger.i(TAG, "clickItemIndex : " + clickItemIndex);
                if (null != orderItemModel) {
                    switch (oprationType) {
                        case 0:
                            if ("All".equals(orderStatus)) {
                                orderItemModel.setIsCancelled(true);
                                orderItemModel.setOrderStatusStr("Cancelled");
                            } else {
                                allPageOrdersList.remove(clickItemIndex);
                                if (allPageOrdersList.size() == 0) {
                                    showEmptyByErrorLayout(orderListView, R.string.no_order_suggest, R.drawable.sorry);
                                }
                            }
                            break;
                        case 1:
                            if ("All".equals(orderStatus)) {
                                orderItemModel.setCanRepay(false);
                                orderItemModel.setIsPaymentCompleted(true);
                                orderItemModel
                                        .setOrderStatusStr("PaymentConfirmed");
                            } else {
                                allPageOrdersList.remove(clickItemIndex);
                                if (allPageOrdersList.size() == 0) {
                                    showEmptyByErrorLayout(orderListView, R.string.no_order_suggest, R.drawable.sorry);
                                }
                            }
                            break;
                        // case 2:
                        // if ("All".equals(orderStatus)) {
                        // orderItemModel.setCanComplete(false);
                        // orderItemModel.setIsCompleted(true);
                        // } else {
                        // allPageOrdersList.remove(clickItemIndex);
                        // }
                        // break;
                        default:
                            break;
                    }
                    adapter.notifyDataSetChanged();
                }
            }

        } else {
            // 下拉刷新数据
            pageIndex = 1;
            if (null == loadingLayout) {
                setView();
                return;
            }
            AsyncTaskUtil.executeTask(new OrdersListAsyncTask(pageIndex, false,
                    true));
        }

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("type", orderStatus);
        super.onSaveInstanceState(outState);
    }

    /**
     * 加载事件
     */
    private void initEvent() {
        // listView的下拉刷新与上拉加载
        orderListView.setScrollingWhileRefreshingEnabled(true);
        orderListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int position, long id) {
                if (id == -1) {
                    return;
                }
                clickItemIndex = position - 1;

                if (null == mContext) {
                    mContext = getActivity();
                }
                if (null == mContext) {
                    return;
                }
                // 单击后进入详情
                Intent intent = new Intent(mContext, OrderDetailActivity.class);
                Bundle b = new Bundle();
                b.putString("OrderNumber",
                        allPageOrdersList.get(position - 1).OrderNumber);
                // b.putSerializable("orderItemModel", orderItemModel);
                intent.putExtras(b);
                startActivityForResult(intent,
                        ServerConstant.Parameter.ORDER_DETAILS_REQUESTCODE);
            }
        });
        orderListView.setOnRefreshListener(new OnRefreshListener2<ListView>() {

            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                // 下拉刷新数据
                pageIndex = 1;
                AsyncTaskUtil.executeTask(new OrdersListAsyncTask(pageIndex,
                        true, true));
            }

            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                // 上拉加载更多数据
                // lv.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
                AsyncTaskUtil.executeTask(new OrdersListAsyncTask(++pageIndex,
                        true, false));
            }
        });

    }

    // +++++++++++++++获取订单数据的任务++++++++++++++++++++++

    protected class OrdersListAsyncTask extends BaseNeedReLoginTask {

        private int start;
        private boolean isDropOrUp;
        private boolean isClearData;

        public OrdersListAsyncTask(int start, boolean isDropOrUp,
                                   boolean isClearData) {
            this.start = start;
            this.isDropOrUp = isDropOrUp;
            this.isClearData = isClearData;
        }

        @Override
        protected void onPreExecute() {
            if (start == 1 && !isDropOrUp) {
                loadingLayout.setVisibility(View.VISIBLE);
                orderListView.setVisibility(View.VISIBLE);
            }

        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                // 客户端Id
                String customerid = GlobalConfig.getInstance()
                        .getUserSessionCfg().getCustomerid();
                if (null == customerid || "".equals(customerid)) {
                    customerid = StringUtil.getConfig(
                            ServerConstant.Parameter.PARAMETER_USER_CUSTOMERID,
                            "0");
                }
                // 调用接口方法获取数据列表集合
                morePageOrdersList = orderServiceProvider.findOrder(customerid,
                        orderStatus, "", start, pageSize, ActivityUtil.getCustomerToken());// Constant.LIST_PAGE_COUNT
                Logger.i("IDI", customerid);
            } catch (DxException e) {
                Log.d(TAG, "erro---" + e.getErrCode());
                return e.getErrCode();
            } catch (Exception e) {
                Logger.e("MyOrdersActivity", "OrdersListAsyncTask", e);
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            Log.d(TAG, "result" + result + " " + morePageOrdersList.size()
                    + " " + orderStatus);
            super.onPostExecute(result);
            if (!isDetached()) {
                // 加载任务执行完毕，隐藏加载视图
                loadingLayout.setVisibility(View.GONE);
                if ("0".equals(result)) {
                    if (allPageOrdersList != null
                            && allPageOrdersList.size() != 0) {
                        Log.d(TAG, allPageOrdersList.get(0).getOrderNumber());
                        if (isClearData) {
                            allPageOrdersList.clear();
                        }
                    }
                    if (morePageOrdersList.size() > 0) {
                        allPageOrdersList.addAll(morePageOrdersList);
                        Log.d(TAG,
                                "allPageOrdersList " + allPageOrdersList.size());
                        adapter.notifyDataSetChanged();
                        orderListView.onRefreshComplete();

                        // 集合中的数据是否小于列表每次加载数据数量
                        if (morePageOrdersList.size() < pageSize) {
                            orderListView.setMode(Mode.PULL_FROM_START);
                        } else {
                            orderListView.setMode(Mode.BOTH);
                        }
                    } else {
                        orderListView.onRefreshComplete();
                        if (1 == start) {
                            showEmptyByErrorLayout(orderListView, R.string.no_order_suggest, R.drawable.sorry);
                        } else {
                            orderListView.setMode(Mode.PULL_FROM_START);
                            adapter.notifyDataSetChanged();
                        }
                    }
                    // setData2UI();
                } else if (!isRelogin) {
                    // 加载第一页因网络未连接或者超时显示网络异常页面
                    if (1 == start
                            /*&& (TextUtils
									.equals(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE,
											result)
							
							 * || TextUtils.equals(ServerConstant.ReturnCode.
							 * VALIDATOR_CONNECT_TIMEOUT, result)
							 )*/) {
                        if (ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE.equals(result)) {
                            showErrorLayout(orderListView, R.string.internet_error,
                                    R.string.internet_suggest, R.drawable.no_internet);
                        } else {
                            showErrorLayout(orderListView, R.string.server_busy,
                                    R.string.server_suggest, R.drawable.no_internet);
                        }
                        orderListView.setVisibility(View.GONE);
                        retryBtn.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                hideAllLayout();
                                AsyncTaskUtil
                                        .executeTask(new OrdersListAsyncTask(
                                                start, false, true));
                            }
                        });
                    } else {
                        // if (start == 1) {
                        // orderListView.setVisibility(View.GONE);
                        // emptyLayout.setVisibility(View.VISIBLE);
                        // noDataIcon.setVisibility(View.INVISIBLE);
                        // noDataSuggest.setText(R.string.get_data_fail);
                        // emptyLayout.setOnClickListener(new OnClickListener()
                        // {
                        // @Override
                        // public void onClick(View v) {
                        // // new
                        // // LoadWishListTask(pageIndex).execute();
                        // // excuteTask(pageIndex);
                        // AsyncTaskUtil
                        // .executeTask(new OrdersListAsyncTask(
                        // pageIndex, false, false));
                        // }
                        // });
                        // }
                        orderListView.onRefreshComplete();
                        pageIndex--;
                        orderListView.setMode(Mode.BOTH);
                        AlertToast.alert(mContext,
                                ServerConstant.ReturnCode.MESSAGEMAP
                                        .get(result));
                    }
                }
            }

        }

        @Override
        protected Context setContext() {
            return getActivity();
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new OrdersListAsyncTask(start, isDropOrUp, isClearData);
        }

    }

    /**
     * 确认收货
     *
     * @author hf
     * @version [版本号, 2015-8-16]
     * @see [相关类/方法]
     * @since [产品/模块版本]
     */
    protected class ConfirmReceptAsyncTask extends
            BaseNeedReLoginTask {
        private String orderNumber;
        private int position;

        public ConfirmReceptAsyncTask(String orderNumber, int position) {
            this.orderNumber = orderNumber;
            this.position = position;
        }

        @Override
        protected void onPreExecute() {
//			showWaitingDialog();
            showLoadingLayout(null);
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                String userName = StringUtil.getConfig(getActivity(),
                        ServerConstant.Parameter.PARAMETER_NAME_USER_ACCOUNT);
                // GlobalConfig.getInstance().getUserSessionCfg().getUsername();
                orderServiceProvider.CompleteOrder(orderNumber, new Operator(
                        userName, "Customer"), userName, ActivityUtil.getCustomerToken(), ActivityUtil.getCustomerID());

            } catch (DxException e) {
                return e.getErrCode();
            } catch (Exception e) {
                Logger.e("MyOrderFragment", "ConfirmReceptAsyncTask", e);
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if (!isDetached()) {
//				hideWaitingDialog();
                hideAllLayout(orderListView);
                if ("0".equals(result)) {
                    if (null != allPageOrdersList
                            && allPageOrdersList.size() > position) {
                        OrderItemModel itemModel = allPageOrdersList
                                .get(position);
                        if (null != itemModel) {
                            if (orderStatus.equals("All")) {
                                itemModel.setIsCompleted(true);
                                itemModel.setCanComplete(false);
                                itemModel.setOrderStatusStr("Completed");
                            } else {
                                allPageOrdersList.remove(position);
                                if (allPageOrdersList.size() == 0) {
                                    showEmptyByErrorLayout(orderListView, R.string.no_order_suggest, R.drawable.sorry);
                                }
                            }
                            adapter.notifyDataSetChanged();
                            if (null != orderComListenner) {
                                orderComListenner.refreshOrderStatus(2,
                                        orderStatus);
                            }
                        }
                    }
                    AlertToast.alert(mContext, R.string.success_recept, 1000);
                } else if (!isRelogin) {
                    // dismissProcessDialog();
                    AlertToast.alert(mContext,
                            ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                }
            }

        }

        @Override
        protected Context setContext() {
            return getActivity();
        }

        @Override
        protected BaseNeedReLoginTask setTask() {
            return new ConfirmReceptAsyncTask(orderNumber, position);
        }
    }

    @Override
    public void orderConfirmRecept(int position) {
        //增加GA跟踪代码
        eventBuilder.setAction("ConfirmRecept");
        tracker.send(eventBuilder.build());
        if (null != allPageOrdersList && allPageOrdersList.size() > position) {
            clickItemIndex = position;
            OrderItemModel itemModel = allPageOrdersList.get(position);
            if (null != itemModel) {
                AsyncTaskUtil.executeTask(new ConfirmReceptAsyncTask(itemModel
                        .getOrderNumber(), position));
            }

        }
    }

    @Override
    public void orderCancel(int position) {
        //增加GA跟踪代码
        eventBuilder.setAction("Cancel");
        tracker.send(eventBuilder.build());
        if (null != allPageOrdersList && allPageOrdersList.size() > position) {
            clickItemIndex = position;
            OrderItemModel itemModel = allPageOrdersList.get(position);
            if (null != itemModel) {
                if (null == mContext) {
                    return;
                }
                Intent intent2 = new Intent(mContext, CancelOrderActivity.class);
                intent2.putExtra("orderNumber", itemModel.getOrderNumber());
                intent2.putExtra("orderPrice",
                        Constant.US_DOLLAR + itemModel.getGrandTotal());
                intent2.putExtra("orderStatus", itemModel.getOrderStatus());
                this.startActivityForResult(intent2,
                        ServerConstant.Parameter.EDIT_REQUESTCODE);
            }
        }

    }

    @Override
    public void orderPay(int position) {
        //增加GA跟踪代码
        eventBuilder.setAction("Pay");
        tracker.send(eventBuilder.build());
        if (null != allPageOrdersList && allPageOrdersList.size() > position) {
            clickItemIndex = position;
            final OrderItemModel itemModel = allPageOrdersList.get(position);
            if (null != itemModel) {
                if (!"840".equals(itemModel.getCurrencyCode())) {
                    Toast.makeText(
                            getActivity(),
                            getResources().getString(
                                    R.string.no_support_payment), 0).show();
                    return;
                }
                if ("5".equals(itemModel.getLight())) {
                    Toast.makeText(
                            getActivity(),
                            getResources().getString(
                                    R.string.no_support_partial_payment), 0)
                            .show();
                    return;
                }
                final boolean canRepay = itemModel.isCanRepay();
                if (!canRepay) {
                    Toast.makeText(getActivity(),
                            getResources().getString(R.string.can_not_pay), 0)
                            .show();
                    return;
                }
                if (null == mContext) {
                    return;
                }
//				showChoosePaymentWindow(itemModel,canRepay);
                int currentVersion = android.os.Build.VERSION.SDK_INT;
                if (14 <= currentVersion && currentVersion < 19) {
                    //4.4以下版本不支持PayPal
                    doCreditPay(itemModel);
                    return;
                }
                //支付方式选择
                PaymentMethodDialogUtils payMethodUtils = new PaymentMethodDialogUtils(new PaymentMethodDialogOnClickListenner() {

                    @Override
                    public void onPayPalClick() {
                        payPalPayment(itemModel, canRepay);
                    }

                    @Override
                    public void onCreditCardClick() {
                        doCreditPay(itemModel);
                    }
                });
                payMethodUtils.showChoosePaymentWindow(mContext);
            }
        }

    }

    /**
     * 信用卡支付
     */
    private void doCreditPay(final OrderItemModel itemModel) {
        Log.i("Ttt", "onCreditCardClick");
        //获取信用卡列表信息
        AsyncTaskUtil.executeTask(new GetCreditCardInfoAsyncTask(new GetCreditCardInfoListenner() {

            @Override
            public void onPreGetInfo() {
                Log.i("Ttt", "onPreGetInfo");
                showLoadingLayout(null);

            }

            @Override
            public void onGetInfoComplect(
                    CreditCardInfo creditCardInfo) {
                ArrayList<SimpleCreditCard> simpleCreditCards = (ArrayList<SimpleCreditCard>) creditCardInfo
                        .getsCreditCards();
                Intent intent = new Intent();
                String type = creditCardInfo.getGatewayType();
                if (null == simpleCreditCards || simpleCreditCards.size() == 0) {
                    intent.setClass(mContext, AddCreditCardActivity.class);
                    intent.putExtra("fromPage", "toPay");
                } else {
                    intent.setClass(mContext, CreditCardListActivity.class);
                    intent.putExtra("CardFlow", type);
                    intent.putParcelableArrayListExtra("CreditCards",
                            simpleCreditCards);
                }
                intent.putExtra("CardFlow", type);
                intent.putExtra(ServerConstant.Parameter.PARAMETER_NAME_ORDER_NUMBER, itemModel.getOrderNumber());
                startActivity(intent);

            }

            @Override
            public void onGetInfoFinish() {
                // TODO Auto-generated method stub
                hideAllLayout(orderListView);
            }


        }, mContext, 1));
    }

    /**
     * 显示选择支付方式弹窗
     * */
/*	AlertDialog dialog;
	private void showChoosePaymentWindow(final OrderItemModel itemModel,final boolean canRepay){
		Builder builder = new AlertDialog.Builder(mContext);
		View v = LinearLayout.inflate(mContext, R.layout.dialog_choose_payment, null);
		RelativeLayout paypal = (RelativeLayout) v.findViewById(R.id.payment_method_paypal);
		RelativeLayout creditcard = (RelativeLayout) v.findViewById(R.id.payment_method_creditcard);
		paypal.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO 执行钱包支付逻辑
				Toast.makeText(mContext, "paypal>>", 0).show();
				Intent intent = new Intent(mContext, CheckoutActivity.class);
				// 传递一个标识，表示从mycartActivity付款的，此时付款完成后需要删除购物车的商品
				intent.putExtra(
						ServerConstant.Parameter.PARAMETER_NAME_FROM_ACTIVITY,
						ServerConstant.ActionConstant.FORM_ORDERLIST_ACTIVITY);

				boolean IsPaymentCompleted = itemModel.isIsPaymentCompleted();
				boolean isPartPay = false;
				if ("5".equals(itemModel.getLight()) && canRepay
						&& !IsPaymentCompleted) {
					isPartPay = true;
				}
				intent.putExtra("isPartPay", isPartPay);
				if (isPartPay) {
					intent.putExtra("DueAmount", itemModel.getDueAmount());
				}
				intent.putExtra("orderNumber", itemModel.getOrderNumber());
				startActivityForResult(intent,
						ServerConstant.Parameter.PAYMENT_RESULTCODE);
				// startActivity(intent);
				dialog.dismiss();
			}
		});
		creditcard.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO 执行信用卡支付逻辑
				Toast.makeText(mContext, "creditcard>>", 0).show();
				Intent i = new Intent(mContext,CreditCardListActivity.class);
				startActivity(i);
				dialog.dismiss();
			}
		});
		builder.setView(v);
		dialog = builder.create();
		dialog.show();
	}*/

    /**
     * Paypal支付
     *
     * @param canRepay
     */
    private void payPalPayment(final OrderItemModel itemModel, final boolean canRepay) {
        Intent intent = new Intent(mContext, CheckoutActivity.class);
        // 传递一个标识，表示从mycartActivity付款的，此时付款完成后需要删除购物车的商品
        intent.putExtra(
                ServerConstant.Parameter.PARAMETER_NAME_FROM_ACTIVITY,
                ServerConstant.ActionConstant.FORM_ORDERLIST_ACTIVITY);

        boolean IsPaymentCompleted = itemModel.isIsPaymentCompleted();
        boolean isPartPay = false;
        if ("5".equals(itemModel.getLight()) && canRepay
                && !IsPaymentCompleted) {
            isPartPay = true;
        }
        intent.putExtra("isPartPay", isPartPay);
        if (isPartPay) {
            intent.putExtra("DueAmount", itemModel.getDueAmount());
        }
        intent.putExtra("orderNumber", itemModel.getOrderNumber());
        startActivityForResult(intent,
                ServerConstant.Parameter.PAYMENT_RESULTCODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Logger.i(TAG, "resultCode: " + resultCode);
        int refreshIndex = -1;
        switch (resultCode) {
            case ServerConstant.Parameter.CANCEL_RESULTCODE:// 取消订单
                refreshIndex = 0;
                break;
            case ServerConstant.Parameter.PAYMENT_RESULTCODE:
                refreshIndex = 1;
                break;
            case ServerConstant.Parameter.ORDER_DETAILS_REQUESTCODE:
                if (null != data) {
                    refreshIndex = data.getIntExtra("type", 0);
                }
                break;
            default:
                break;
        }
        if (refreshIndex != -1) {
            Logger.i(TAG, "resultCoderefreshIndex : " + refreshIndex);
            refreshOrderStatus(true, refreshIndex);
            if (null != orderComListenner) {
                orderComListenner.refreshOrderStatus(refreshIndex, orderStatus);
            }
        }

    }

    @Override
    public void checkShippingInfo(String orderNumber, String currencyCode) {
        // 跳转到shippingInfo
        Intent i = new Intent(mContext, ShippingTrackingActivity.class);
        i.putExtra("OrderNumber", orderNumber);
        i.putExtra("CurrencyCode", currencyCode);
        startActivity(i);
    }
}
